import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

part_class_router = APIRouter(prefix="/part/partClass", tags=["备件分类管理"], dependencies=[Depends(oauth2_scheme)])

from pydantic import BaseModel, Field
from typing import Optional


class SparePartCategorySearch(PaginationBase):
    # 筛选条件
    fclassstname: Optional[str] = Field("", description="分类名称(支持前缀匹配)")
    fparentno: Optional[str] = Field("", description="父级分类编号")


@part_class_router.get("/list", summary="备件分类查询接口")
def list_part_class(search: SparePartCategorySearch=Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_part_class where 1=1"
    if search.fclassstname != "":
        sql = sql + " and fclassstname like concat('%', :fclassstname ,'%')"
        param["fclassstname"] = search.fclassstname
    if search.fparentno != "":
        sql = sql + " and fparentno = :fparentno "
        param["fparentno"] = search.fparentno
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fclassstno,fclassstname,fparentno,fclassstyle,flevel,fdiscmonth,fupddate,foperator"
    sql = sql + " from s_ts_part_class where 1=1"
    if search.fclassstname != "":
        sql = sql + " and fclassstname like concat('%', :fclassstname ,'%')"
        param["fclassstname"] = search.fclassstname
    if search.fparentno != "":
        sql = sql + " and fparentno = :fparentno "
        param["fparentno"] = search.fparentno
    if search.order == "desc":
        sql = sql + " order by  fclassstno desc "
    else:
        sql = sql + " order by  fclassstno "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fclassstno'] = data[key][0]
        d1['fclassstname'] = data[key][1]
        d1['fparentno'] = data[key][2]
        d1['fclassstyle'] = data[key][3]
        d1['flevel'] = data[key][4]
        d1['fdiscmonth'] = data[key][5]
        d1['fupddate'] = data[key][6]
        d1['foperator'] = data[key][7]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class SparePartCategoryCreate(BaseModel):
    """备件分类新增请求参数"""
    fclassstno: str = Field(..., description="分类编号")
    fclassstname: str = Field(..., description="分类名称")
    fdiscmonth: int = Field(..., description="折旧月份")
    fparentno: str = Field(..., description="父级分类编号")
    foperator: str = Field(..., description="操作人ID")
    fupddate: str = Field(..., description="更新日期(格式需与数据库存储一致)")


@part_class_router.post("/create", summary="备件分类新增接口")
def create_part_class(create: SparePartCategoryCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fclassstno from s_ts_part_class where fclassstno= :fclassstno "
            data = db.execute(text(sql), {
                "fclassstno": create.fclassstno
            }).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_part_class(fclassstno,fclassstname,fdiscmonth,fparentno,fupddate,foperator)"
                sql = sql + " values( :fclassstno , :fclassstname , :fdiscmonth , :fparentno , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "fclassstno": create.fclassstno,
                    "fclassstname": create.fclassstname,
                    "fdiscmonth": create.fdiscmonth,
                    "fparentno": create.fparentno,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator
                })
                data = {"fclassstno": create.fclassstno
                    , "fclassstname": create.fclassstname
                    , "fdiscmonth": create.fdiscmonth
                    , "fparentno": create.fparentno
                    , "fupddate": create.fupddate
                    , "foperator": create.foperator
                        }
                return BaseResponse.success(data=data)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@part_class_router.post("/update", summary="备件分类修改接口")
def update_part_class(update: SparePartCategoryCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_part_class"
            sql = sql + " set fclassstname= :fclassstname ,fparentno= :fparentno "
            sql = sql + ",fdiscmonth= :fdiscmonth "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fclassstno= :fclassstno "
            db.execute(text(sql), {
                "fclassstname": update.fclassstname,
                "fparentno": update.fparentno,
                "fdiscmonth": update.fdiscmonth,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "fclassstno": update.fclassstno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@part_class_router.post("/delete/{fclassstno}", summary="备件分类删除接口")
def delete_part_class(fclassstno: str = Path(description="备件分类编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from s_ts_part_class where fclassstno= :fclassstno "
            db.execute(text(sql), {
                "fclassstno": fclassstno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
